package cn.com.dotleo.summarize;

/**
 * Created by liufei on 2018/6/16.
 */
public class SynchronizedDemo {

    // 共享变量
    private boolean ready = false;
    private int result = 0;
    private int number = 1;

    // 写操作
    public void write() {
        ready = true;  // 1.1
        number = 2;  // 1.2
    }

    // 读操作
    public void read() {
        if (ready) {  // 2.1
            result = number * 3;  //2.2
        }
        System.out.println("result的值为:" + result);
    }

    private class ReadWriteThread extends Thread {
        private boolean flag;
        public ReadWriteThread(boolean flag) {
            this.flag = flag;
        }

        // 根据传入执行不同的读写操作
        @Override
        public void run() {
            if (flag) {
                write();
            } else {
                read();
            }
        }
    }

    public static void main(String[] args) {
        SynchronizedDemo demo = new SynchronizedDemo();
        // 启动写线程
        demo.new ReadWriteThread(true).start();
        // 启动读线程
        demo.new ReadWriteThread(false).start();
    }

}
